"use strict"

var Router = require('koa-router');
var config = require('../../config/config.js');
var debug = require('debug')('router_role');
var dao = require('../../dao/role.js');
var ferror = require('../../common/app_utils.js').formatError;
var errInfo = require('../../common/err_info.js');

debug('router:' + config.http.baseUrl + '/v1/role');
var router = new Router({
	prefix: config.http.baseUrl + '/v1/role'
});

/*
{	
"name":"role_vendor",
"description":"商家",
"permissions":[123,456]
}
 */
router.post('/', function*() {
	// check input TODO
	var inParams = this.request.inParams;
	debug('add role', inParams);
	inParams.permissions = __normalInput(inParams.permissions);
	var result = yield dao.create(inParams);
	this.body = result;
});

function __normalInput(permissions) {
	var tmp = [];
	if (!permissions) {
		// do nothing
	} else if (Array.isArray(permissions)) {
		tmp = permissions.map(function(item) {
			return Number(item);
		});
	} else {
		tmp.push(Number(permissions));
	}
	return tmp;
}

// edit a role
router.put('/', function*() {
	var inParams = this.request.inParams;
	inParams.permissions = __normalInput(inParams.permissions);
	debug('edit role', JSON.stringify(inParams));
	// check input TODO
	var result = yield dao.update(inParams);
	this.body = result;
});

// get all permissions
router.get('/list', function*() {
	var inParams = this.request.inParams || {};
	inParams.userId = this.session.userId;

	var result = yield dao.readAll(inParams);
	this.body = result;
});

// get one role
router.get('/:id', function*() {
	var inParams = this.params;
	// debug('get /:id', inParams);
	if (!inParams.id) {
		this.status = 400;
		this.body = 'should have field id';
		return;
	}
	inParams.userId = this.session.userId;

	var result = yield dao.readById(inParams);
	this.body = result;
});

module.exports = router.routes();